import type { EntityMetadata, ResourceOperation } from './resource';

import type {
  ApiResult,
  FilterGroup,
  IOutDto,
  PageResult,
} from '#/utils/daprplus';

import { requestClient } from '#/api/request';

import { ResourceType } from './resource';

export interface ResourceNode extends IOutDto {
  id: string;
  name: string;
  code: string;
  description?: string;
  type: ResourceType;
  isSelected: boolean;
  operations: string[];
  allowedOperations: ResourceOperation[];
}

export interface RoleResourceInDto {
  resourceId: string;
  operations: string[];
}

export interface RoleResourceOutDto extends IOutDto {
  roleId: string;
  resourceId: string;
  resourceName: string;
  resourceCode: string;
  resourceMetadataJson?: string;
  operations: string[];
  allowedOperations: ResourceOperation[];
  filterGroups?: Record<string, FilterGroup>;
  entityMetadata?: EntityMetadata;
  createdTime: Date;
  isLocked: boolean;
}

/**
 * 获取用于分配角色权限的实体资源节点
 * @param roleId 角色ID
 * @param service 服务地址前缀
 * @returns 实体资源树
 */
export async function getEntityResourceNodeApi(roleId: string) {
  const url = `/api/resource/node/${roleId}`;
  const result = await requestClient.get<Record<string, ResourceNode[]>>(url, {
    responseReturn: 'data',
  });
  return result;
}

/**
 * 获取角色资源分页数据
 * @param query 查询条件
 * @param service 服务地址前缀
 * @returns 角色资源分页数据
 */
export async function getRoleResourcePageApi(query: any, service: string) {
  const url = `/api/roleresource/page`;
  const result = await requestClient.post<PageResult<RoleResourceOutDto>>(
    url,
    { service, query },
    {
      responseReturn: 'data',
    },
  );
  return { items: result.data, total: result.total };
}

/**
 * 设置角色资源权限
 * @param roleId 角色ID
 * @param dict 角色资源数据
 * @param service 服务地址前缀
 * @returns 操作结果
 */
export async function setRoleResourceApi(
  roleId: string,
  dict: Record<string, RoleResourceInDto[]>,
) {
  const url = `/api/roleresource/setrole`;
  const result = await requestClient.post<ApiResult>(url, {
    roleId,
    dict,
  });
  return result;
}

/**
 * 设置角色资源过滤条件组
 * @param resourceId 资源ID
 * @param roleId 角色ID
 * @param filterGroups 各操作的过滤条件组
 * @param service 服务地址前缀
 * @returns 操作结果
 */
export async function setFilterGroupsApi(
  resourceId: string,
  roleId: string,
  filterGroups: Record<string, FilterGroup>,
  service: string,
) {
  const url = `/api/roleresource/setfilters`;
  const result = await requestClient.post<ApiResult>(url, {
    service,
    resourceId,
    roleId,
    filterGroups,
  });
  return result;
}
